package servlet;

import pojo.Book;
import pojo.Category;
import service.BookService;
import service.BookServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Tiler on 2020/11/4
 */
public class AddOneBook extends HttpServlet {
    private BookService bookService = new BookServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html");
        resp.setCharacterEncoding("UTF-8");

        Integer publisherId = Integer.parseInt(req.getParameter("publisher"));
        String[] categories = req.getParameterValues("category");

        //将分类id转换为分类对象列表
        List<Category> list = new ArrayList<>();
        for (String c : categories) {
            Category category = new Category();
            category.setCategoryId(Integer.parseInt(c));

            list.add(category);
        }

        Book book = new Book();
        book.setBookName(req.getParameter("bookName"));
        book.setImage(req.getParameter("image"));
        book.setPublisherId(publisherId);
        book.setCategories(list);

        if (bookService.addOneBook(book) > 0) {
            req.setAttribute("message", "新增成功");
        }
        else {
            req.setAttribute("message", "新增失败");
        }

        req.getRequestDispatcher("get_message.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
